//
//  DXMLNoteObject.m
//  DerbyStatter
//
//  Created by glenn andreas on 1/6/14.
//  Copyright (c) 2014 glenn andreas. All rights reserved.
//

#import "DXMLNoteObject.h"

@implementation DXMLNoteObject

@end


@implementation DXMLObject(Notes)
- (NSString *) notes
{
    NSMutableArray *notes = [NSMutableArray array];
    for (DXMLObject *child in self.children) {
        if ([[child elementName] isEqualToString:@"note"]) {
            if (child.text)
                [notes addObject:child.text];
        }
    }
    return [notes componentsJoinedByString:@"\n"];
}
- (void) setNotes:(NSString *)notes
{
    // go through each line, replace existing notes with the line, and remove/add extra as needed
    NSMutableArray *noteArray = [[notes componentsSeparatedByString:@"\n"] mutableCopy];
    NSMutableArray *toRemove = [NSMutableArray array];
    for (DXMLObject *child in self.children) {
        if ([[child elementName] isEqualToString:@"note"]) {
            if (noteArray.count) {
                child.text = noteArray[0];
                [noteArray removeObject:noteArray[0]];
            } else {
                [toRemove addObject:child]; // no longer needed
            }
        }
    }
    for (DXMLObject *child in toRemove) {
        [self removeChild:child];
    }
    for (NSString *noteText in noteArray) {
        // add any left
        DXMLNoteObject *note= [[DXMLNoteObject alloc] initWithElementName:@"note" attributes:nil];
        note.text = noteText;
        [self addChild:note];
    }
    
}
@end